package com.bluefuture.modules.sys.security.handler;

import com.google.gson.Gson;
import com.bluefuture.common.utils.HttpContextUtils;
import com.bluefuture.common.utils.HttpStatus;
import com.bluefuture.common.utils.R;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Clown
 */
@Component
public class TokenAccessDeniedHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AccessDeniedException e) throws IOException, ServletException {
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", HttpContextUtils.getOrigin());
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setCharacterEncoding("UTF-8");
        String json = new Gson().toJson(R.error(HttpStatus.FORBIDDEN, "无权限"));

        httpServletResponse.getWriter().print(json);
    }
}
